package com.spa.infrastructure.repository.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.spa.infrastructure.util.StringUtils;
import com.spa.infrastructure.repository.condition.SysRoleCondition;
import com.spa.infrastructure.repository.mapper.SysRoleMapper;
import com.spa.infrastructure.repository.po.SysRolePO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class SysRoleRepositoryService extends MPJBaseServiceImpl<SysRoleMapper, SysRolePO> {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    public int saveRole(SysRolePO po) {
        return sysRoleMapper.insert(po);
    }

    public Page<SysRolePO> page(SysRoleCondition condition) {
        return page(Page.of(condition.getCurrent(), condition.getSize()), wrapper(condition));
    }

    public List<SysRolePO> list(SysRoleCondition condition) {
        return list(wrapper(condition));
    }

    public void updateRoleByCondition(SysRolePO po) {
        update(null, updateWrapper(po));
    }

    private LambdaQueryWrapper<SysRolePO> wrapper(SysRoleCondition condition) {
        LambdaQueryWrapper<SysRolePO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(StringUtils.isNotNull(condition.getRoleName()),SysRolePO::getRoleName,condition.getRoleName());
        wrapper.orderByAsc(SysRolePO::getRoleSort);
        return wrapper;
    }

    private LambdaUpdateWrapper<SysRolePO> updateWrapper(SysRolePO po) {
        LambdaUpdateWrapper<SysRolePO> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(SysRolePO::getRoleId, po.getRoleId());
        updateWrapper.set(StringUtils.isNotEmpty(po.getRoleName()), SysRolePO::getRoleName, po.getRoleName());
        return updateWrapper;
    }

}
